<?php
# Generates CSS, JS or <head> JS for a ?style in a ?site
error_reporting(E_ALL);
ini_set('display_errors', true);

header('Content-type: text/plain');

define('DOCROOT', realpath(dirname(__FILE__) . '/../') . '/');
define('WEBROOT', str_replace('Utils/', '', str_replace('//', '/', dirname($_SERVER['SCRIPT_NAME']) . '/')));

include DOCROOT . 'Core/Functions.php';

# Make sure all params are set
$site		= isset($_GET['site']) ? basename($_GET['site']) : false;
$style		= isset($_GET['style']) ? basename($_GET['style']) : false;
$type		= isset($_GET['type']) ? basename($_GET['type']) : 'scss';
$output		= '';

if (!$site or !$style or !$type) {
	die('Please specify ?site, ?style and ?type');
}

# Convert type to file matching regexp
$regexps	= array(
	'scss'		=> 'CSS/*.scss', 
	'js'		=> 'JS/[!head-]*.js', 
	'js_head'	=> 'JS/head-*.js'
);

$newRegexps	= array(
	'scss'		=> '*.scss', 
	'js'		=> '[!head-]*.js', 
	'js_head'	=> 'head-*.js'
);

$typeToDir = array(
	'scss'		=> 'CSS', 
	'js'		=> 'JS', 
	'js_head'	=> 'JS'
);

# Make sure site and style exists
$sitePath	= file_exists(DOCROOT . "Sites/$site/$site.info") ? DOCROOT . "Sites/$site/$site.info" : false;

if ($sitePath and isset($regexps[$type])) {
	# Grab .info-data to know which sites and styles to extend
	$siteData 	= extractKeyValArray(file_get_contents($sitePath));
	$sites		= array_merge(array($site), tunnArray(explode(' ', trim((isset($siteData['extends']) ? $siteData['extends'] : '')))));

	# Now that we know which sites to look in, find the style
	$stylePath = false;

	foreach (array_reverse($sites) as $s) {
		if (file_exists(DOCROOT . "Sites/$s/Styles/$style/$style.info")) {
			$stylePath = DOCROOT . "Sites/$s/Styles/$style/$style.info";

			break;
		}
	}

	if ($stylePath) {
		$styleData		= extractKeyValArray(file_get_contents($stylePath));
		$styles			= array_merge(array($style), tunnArray(explode(' ', trim((isset($styleData['extends']) ? $styleData['extends'] : '')))));
		$modulesArray	= array();
		$stylesArray	= array();

		# Merge all module CSS
		foreach (array_reverse($sites) as $site) {
			$path = DOCROOT . "Sites/$site/Modules";

			if (is_dir($path)) {
				foreach (glob("$path/*/{$typeToDir[$type]}/") as $dir) {
					$tmp = array();

					foreach (glob("{$dir}{$newRegexps[$type]}") as $file) {
						$tmp["/* $file */\n" . file_get_contents($file) . "\n"] = basename($file);
					}

					asort($tmp);

					$modulesArray = array_merge($modulesArray, $tmp);
				}
			}
		}

		# Merge all style CSS
		foreach (array_reverse($styles) as $style) {
			foreach (array_reverse($sites) as $site) {
				$path = DOCROOT . "Sites/$site/Styles/$style";

				if (is_dir($path)) {
					foreach (glob("$path/{$typeToDir[$type]}/") as $dir) {
						$tmp = array();

						foreach (glob("{$dir}{$newRegexps[$type]}") as $file) {
							$tmp["/* $file */\n" . file_get_contents($file) . "\n"] = basename($file);
						}

						asort($tmp);

						$stylesArray = array_merge($stylesArray, $tmp);
					}
				}
			}
		}

		# Loop all modules and styles' CSS
		foreach ($modulesArray as $content => $path) {
			$output .= $content;
		}

		foreach ($stylesArray as $content => $path) {
			$output .= $content;
		}

		# TODO: Add support for Config.no_sass
		# All files merged, now do some packing and SASSing etc
		if ($type == 'scss') {
			# Give SCSS authors access to WEB and DOCROOT
			$output = '$WEBROOT: "' . WEBROOT . "\";\n\n" . $output;
			$output = '$DOCROOT: "' . DOCROOT . "\";\n\n" . $output;

			# Replace them from here due to what seems like a SASS bug?
			$output = str_replace('#{$DOCROOT}', DOCROOT, $output);
			$output = str_replace('#{$WEBROOT}', WEBROOT, $output);

			# Write the SASS code to the .scss output file
			file_put_contents(DOCROOT . "Sites/$site/Styles/$style.scss", $output);

			# Run SASS on said file, save as .css file
			$exec = 'sass ' . DOCROOT . "Sites/$site/Styles/$style.scss " . DOCROOT . "Sites/$site/Styles/$style.css"; # --style=compressed

			exec($exec);

			# With CSSTidy
			if (isset($styleData['csstidy']) and $styleData['csstidy'] !== false) {
				include DOCROOT . 'Lib/CSSTidy/class.csstidy.php';

				# Read generated CSS file
				$tidyCSS = file_get_contents(DOCROOT . "Sites/$site/Styles/$style.css");
				$cssTidy = new csstidy();

				$cssTidy->parse($tidyCSS);
				$cssTidy->set_cfg('remove_last_;', true);

				# Write new, tidy CSS file
				file_put_contents(DOCROOT . "Sites/$site/Styles/$style.css", $cssTidy->print->plain());
			}

			echo "DONE!";
		}
		else {
			include DOCROOT . 'Lib/JavaScriptPacker.php';

			$packer = new JavaScriptPacker($output, 0);

		#	$output = $packer->pack();

			if ($type == 'js_head') {
				file_put_contents(DOCROOT . "Sites/$site/Styles/$style.head.js", $output);
				echo "DONE!";
			}
			else {
				file_put_contents(DOCROOT . "Sites/$site/Styles/$style.js", $output);
				echo "DONE!";
			}
		}	
	}
	else {
		echo '?style does not exist in your site or any of your extended sites';
	}
}
else {
	echo '?site does not exist or ?type is wrong';
}
